package com.gonfre.quientelo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

import util.DataBaseManager;
import util.FilterValues;
import util.MyDBObject;
import util.MyDataBase;
import util.RangeSeekBar;
import util.Tools;


public class FiltersFragment extends Fragment {

    //Options to initialize
    public static final int PURCHASER = 0;
    public static final int SELLER    = 1;

    //Another Options
    public static final int CATEGORIES = 0;
    public static final int LOCATIONS  = 1;
    public static final int PHOTOS     = 2;

    //Groups
    private RelativeLayout layoutPrice;
    private RelativeLayout layoutCategory;
    private RelativeLayout layoutLocation;
    private RelativeLayout layoutPhoto;

    //Components
    private RangeSeekBar<Integer> seekBar;
    private TextView txtPreDesde;
    private TextView txtPreHasta;
    private LinearLayout grpCategories;
    private LinearLayout grpLocations;
    private LinearLayout grpPhotos;

    //Buttons
    private Button okButton;
    private Button cancelButton;

    //All values
    private FilterValues currentValues;
    private int userType = SELLER;

    /* METHODS */

    public FiltersFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_filters, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Get Groups
        layoutPrice    = (RelativeLayout)getActivity().findViewById(R.id.layoutPrecio);
        layoutCategory = (RelativeLayout)getActivity().findViewById(R.id.layoutCategorias);
        layoutLocation = (RelativeLayout)getActivity().findViewById(R.id.layoutUbicaciones);
        layoutPhoto    = (RelativeLayout)getActivity().findViewById(R.id.layoutFotos);

        //Get Components
        txtPreDesde   = (TextView)getActivity().findViewById(R.id.txtPreDesde);
        txtPreHasta   = (TextView)getActivity().findViewById(R.id.txtPreHasta);
        grpCategories = (LinearLayout)getActivity().findViewById(R.id.grpCategories);
        grpLocations  = (LinearLayout)getActivity().findViewById(R.id.grpLocations);
        grpPhotos     = (LinearLayout)getActivity().findViewById(R.id.grpPhotos);

        // Get Buttons
        okButton     = (Button) getActivity().findViewById(R.id.btnFilterOk);
        cancelButton = (Button) getActivity().findViewById(R.id.btnFilterCancel);

        // Add Listeners to buttons
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetWidgetsFromValues();
                ((MyActivity)getActivity()).onFilterBarCancelPressed();
            }
        });

        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateValuesFromWidgets();
                ((MyActivity)getActivity()).onFilterBarOkPressed(currentValues);
            }
        });

        //Initialize
        initialize();
    }

    private void createSeekBar(int min, int max) {
        seekBar = new RangeSeekBar<Integer>(min, max, getActivity());
        seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
                txtPreDesde.setText(Tools.getShowRangeBarValue(minValue));
                txtPreHasta.setText(Tools.getShowRangeBarValue(maxValue));
            }
        });

        LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.layoutRangeBar);
        layout.addView(seekBar);
    }

    public void setUserType(int type) {
        userType = type;
    }

    /* ANOTHER METHODS */

    private void updateCheckedValues(LinearLayout grp, List list) {
        for (int i = 0; i<grp.getChildCount(); i++) {
            CheckBox ch = (CheckBox)grp.getChildAt(i);
            if (ch.isChecked()) {
                list.add(ch.getHint().toString());
            }
        }
    }

    private void updateValuesFromWidgets() {
        //Prices
        currentValues.setPriceMin(Tools.getNoShowRangeBarValue(seekBar.getSelectedMinValue()));
        currentValues.setPriceMax(Tools.getNoShowRangeBarValue(seekBar.getSelectedMaxValue()));

        //Lists
        currentValues.clearLists();

        updateCheckedValues(grpCategories, currentValues.getCategories());
        updateCheckedValues(grpLocations, currentValues.getLocations());
        updateCheckedValues(grpPhotos, currentValues.getPhotos());
    }

    private void resetCheckBoxes(LinearLayout grp, List list) {
        for (int i = 0; i<grp.getChildCount(); i++) {
            CheckBox ch = (CheckBox)grp.getChildAt(i);
            if (list.contains(ch.getHint().toString())) {
                ch.setChecked(true);
            } else {
                ch.setChecked(false);
            }
        }
    }

    private void resetWidgetsFromValues() {
        // Prices
        //txtPreDesde.setText( Tools.getFormatValue( currentValues.getPriceMin() ) );
        //txtPreHasta.setText( Tools.getFormatValue( currentValues.getPriceMax() ) );
        updateSeekBar();

        //Lists
        resetCheckBoxes(grpCategories, currentValues.getCategories());
        resetCheckBoxes(grpLocations, currentValues.getLocations());
        resetCheckBoxes(grpPhotos, currentValues.getPhotos());
    }

    private void updateSeekBar() {
        seekBar.setSelectedMinValue(Tools.getRangeBarValue(currentValues.getPriceMin()));
        seekBar.setSelectedMaxValue(Tools.getRangeBarValue(currentValues.getPriceMax()));

        txtPreDesde.setText(Tools.getFormatValue(currentValues.getPriceMin()));
        txtPreHasta.setText(Tools.getFormatValue(currentValues.getPriceMax()));
    }

    private void initialize() {
        // Hide groups
        if (userType == SELLER) {
            layoutPrice.setVisibility(View.GONE);
        } else {
            layoutLocation.setVisibility(View.GONE);
        }
    }

    private void createWidgets() {
        //Create checkboxes
        createCheckBoxes(CATEGORIES);
        createCheckBoxes(LOCATIONS);

        //init prices
        int minVal = Tools.calculateRangeMinVal(currentValues.getPriceMin());
        int maxVal = Tools.calculateRangeMaxVal(currentValues.getPriceMax());
        createSeekBar( minVal, maxVal );
        currentValues.setPricesLimits(minVal, maxVal);
        txtPreDesde.setText( Tools.getShowRangeBarValue(minVal) );
        txtPreHasta.setText( Tools.getShowRangeBarValue(maxVal) );
    }

    private void createCheckBoxes(int type) {
        LinearLayout grp = null;
        List<String> list = null;

        if (type == CATEGORIES) {
            grp = grpCategories;
            list = currentValues.getCategories();
            currentValues.setCategoriesMaxSize(list.size());
        } else if (type == LOCATIONS) {
            grp = grpLocations;
            list = currentValues.getLocations();
            currentValues.setLocationsMaxSize(list.size());
        } else {
            //NOTHING
        }

        for (int i=0; i<list.size(); i++) {
            CheckBox ch = createCheckBox(list.get(i), type);
            grp.addView(ch);
        }
    }

    private CheckBox createCheckBox(String value, int type) {
        CheckBox ch = new CheckBox(getActivity());
        ch.setHint( value );
        ch.setTextAppearance(getActivity(), R.style.RadioButton);
        String text = value;

        if (type == CATEGORIES) {
            try {
                DataBaseManager dbm = new DataBaseManager((MyActivity)getActivity());
                String table = this.getString(R.string.table_categoria);
                String sql_table = this.getString(R.string.sql_categoria);
                MyDataBase dbCategories = new util.MyDataBase((MyActivity)getActivity(), dbm, table, sql_table);

                String query_get_one_category = this.getString(R.string.query_get_one_category);
                MyDBObject[] myObjs = dbCategories.readItemCategory(query_get_one_category, value, "nombre", "id", "icono");

                if (myObjs.length > 0) {
                    text = myObjs[0].objectName;
                }
            } catch (Exception _e) { }
        } else if (type == LOCATIONS) {
            try {
                DataBaseManager dbm = new DataBaseManager((MyActivity)getActivity());
                String table = this.getString(R.string.table_ubicacion);
                String sql_table = this.getString(R.string.sql_ubicacion);
                MyDataBase dbLocations = new util.MyDataBase((MyActivity)getActivity(), dbm, table, sql_table);

                String query_get_one_location = this.getString(R.string.query_get_one_location);
                MyDBObject[] myObjs = dbLocations.readItem(query_get_one_location, value, "ubicacion", "id");

                if (myObjs.length > 0) {
                    text = myObjs[0].objectName;
                }
            } catch (Exception _e) { }
        } else {
            //NOTHING
        }

        ch.setText(text);
        ch.setChecked(true);

        return ch;
    }

    public void setInitialValues(FilterValues values) {

        currentValues = values;

        //initialize
        createWidgets();
    }
}
